package com.leyou.gateway.filters;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

import static com.leyou.auth.constants.JwtConstants.KEY_PREFIX;

@Component
@Order(0)
@Slf4j
public class LoginFilter implements GlobalFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        try {
            ServerHttpRequest request = exchange.getRequest();

            String token = request.getCookies().toSingleValueMap().get("LY_TOKEN").getValue();


            Payload payload = jwtUtils.parseJwt(token);

            String key = KEY_PREFIX + payload.getUserDetail().getUsername();

            //重置当前key超时时间30
            redisTemplate.expire(key, 30, TimeUnit.MINUTES);

        } catch (Exception e) {
            //没有登录直接放行

            log.info("用户未登录");
        }


        return chain.filter(exchange);
    }
}
